<?php

namespace App\Morefun\Prize;


use App\Entities\Prize;
use App\Entities\PrizeRecord;
use BadMethodCallException;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;

class Flow
{
    protected $prizeId;

    /**
     * @param $prizeId
     * @return Flow
     */
    public function witch($prizeId)
    {
        $this->prizeId = $prizeId;

        return $this;
    }

    /**
     * @param $operate
     * @param $quantity
     * @param $lockByActivityId
     * @return bool
     */
    public function record($operate, $quantity, $lockByActivityId = null)
    {
        if (!Uuid::isValid($this->prizeId)) {
            throw new BadMethodCallException('Please pre-call Flow::witch($prizeId)');
        }

        if (!array_key_exists($operate, PrizeRecord::ENTITY_OPERATES)) {
            throw new InvalidArgumentException("Invalid prize record operate: {$operate}");
        }

        $prizeId = $this->prizeId;
        $this->prizeId = null;

        $flow = new PrizeRecord();
        $flow->setAttribute('prize_id', $prizeId);
        $flow->setAttribute('operate', $operate);
        $flow->setAttribute('number', $quantity + 0);

        if (Uuid::isValid($lockByActivityId)) {
            $flow->setAttribute('activity_id', $lockByActivityId);
        }

        $flow->setAttribute('summary', $this->calculateMotherFuckSummary($prizeId, $operate, $quantity));

        return $flow->save();
    }

    /**
     * 计算屎一样设计的流水
     * @param $prizeId
     * @param $operate
     * @param $quantity
     * @return integer
     */
    protected function calculateMotherFuckSummary($prizeId, $operate, $quantity)
    {
        $lastSummary = PrizeRecord::query()->where('prize_id', $prizeId)
            ->orderBy('updated_at', 'DESC')
            ->value('summary');

        if (in_array($operate, [PrizeRecord::CREATE, PrizeRecord::ENTRY, PrizeRecord::RECYCLE], false)) {
            $lastSummary += $quantity;
        }

        if (PrizeRecord::DELIVERY == $operate) {
            $lastSummary -= $quantity;
        }

        return $lastSummary;
    }
}
